#include "cc_cond.h"
#include "cc_log.h"

void cc_cond_init(cc_cond_t cond)
{
  if (cond == CC_NULL)
  {
    cc_log_e("cond is null\r\n");
    return;
  }
  cond->len = 0;
  cc_sem_init(&cond->sem, 0, CC_CONFIG_THREAD_NUM_MAX);
}

cc_cond_t cc_cond_create()
{
  cc_cond_t cond = (cc_cond_t)malloc(sizeof(cc_cond));
  if (cond == CC_NULL)
  {
    cc_log_e("cond is null\r\n");
    return CC_NULL;
  }
  cc_cond_init(cond);
  return cond;
}

void cc_cond_deinit(cc_cond_t cond)
{
  if (cond == CC_NULL)
  {
    cc_log_e("cond is null\r\n");
    return;
  }
  cc_sem_deinit(&cond->sem);
}
void cc_cond_destory(cc_cond_t cond)
{
  if (cond == CC_NULL)
  {
    cc_log_e("cond is null\r\n");
    return;
  }
  cc_cond_deinit(cond);
  cc_free(cond);
}
int cc_cond_wait_ms(cc_cond_t cond, uint32_t ms)
{
  if (cond == CC_NULL)
  {
    cc_log_e("cond is null\r\n");
    return CC_ENOMEM;
  }
  cond->len++;
  int ret = cc_sem_wait_time(&cond->sem, ms);
  cond->len--;

  return ret;
}

int cc_cond_wait(cc_cond_t cond)
{
  return cc_cond_wait_ms(cond, CC_TIME_WAIT_FOREVER);
}

int cc_cond_try_wait(cc_cond_t cond)
{
  return cc_cond_wait_ms(cond, 0);
}
int cc_cond_signal(cc_cond_t cond)
{
  if (cond == CC_NULL)
  {
    cc_log_e("cond is null\r\n");
    return CC_ENOMEM;
  }
  return cc_sem_release(&cond->sem);
}

int cc_cond_broadcast(cc_cond_t cond)
{
  if (cond == CC_NULL)
  {
    cc_log_e("cond is null\r\n");
    return CC_ENOMEM;
  }
  int i = 0;
  for (i = 0; i < cond->len; i++)
  {
    (void)cc_cond_signal(cond);
  }
  return CC_EOK;
}
